﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Configuration;
using System.Web;

namespace UpdateService
{

    public class UpdateService : IUpdateService
    {
    
        public string GetVersionInfo()
        {
            try
            {
                if (HttpRuntime.Cache["VersionInfo"] != null)
                    return HttpRuntime.Cache["VersionInfo"].ToString();
                StreamReader reader = new StreamReader(ConfigurationManager.AppSettings["LatestUpdateFilePath"] + "Version.txt");
                string versionInfo = reader.ReadLine();
                reader.Close();
                reader.Dispose();
                HttpRuntime.Cache.Insert("VersionInfo", versionInfo,
                                new System.Web.Caching.CacheDependency(ConfigurationManager.AppSettings["LatestUpdateFilePath"] + "Version.txt"),
                                DateTime.Now.AddMinutes(10), TimeSpan.Zero);
                return versionInfo;
            }
            catch (Exception ex)
            {
                Logging.LogError("GetVersionInfo", ex);
                throw;
            }
        }


        public byte[] GetUpdatePackage()
        {
            try
            {
                if (HttpRuntime.Cache["UpdatePackage"] != null)
                    return (byte[])HttpRuntime.Cache["UpdatePackage"];
                BinaryReader br = new BinaryReader(File.Open(ConfigurationManager.AppSettings["LatestUpdateFilePath"] + "Fredium.zip",
                                                                FileMode.Open, FileAccess.Read));
                br.BaseStream.Position = 0;
                byte[] package = br.ReadBytes(Convert.ToInt32(br.BaseStream.Length));
                br.Close();
                HttpRuntime.Cache.Insert("UpdatePackage", package,
                                new System.Web.Caching.CacheDependency(ConfigurationManager.AppSettings["LatestUpdateFilePath"] + "Fredium.zip"),
                                DateTime.Now.AddMinutes(10), TimeSpan.Zero);
                return package;
            }
            catch (Exception ex)
            {
                Logging.LogError("GetUpdatePackage", ex);
                throw;
            }

        }


        private void PutFile(byte[] buffer, string filename)
        {
            BinaryWriter binWriter = new BinaryWriter(File.Open(HttpContext.Current.Server.MapPath(filename), FileMode.CreateNew, FileAccess.ReadWrite));
            binWriter.Write(buffer);
            binWriter.Close();
        }

    }

}
